<?php
/*

  Хранилище профилей принципала, основанная на таблице в БД

  PrincipalStorage_db( &$principal )
      - $principal       -- к какому принципалу прикрепляться

  -------------------

  Суть структуры:
    * каждый профиль -- строка в соотв. таблице
    * имя таблицы можно перезадать в 
       $rh->principal_storage_model_table = "users"

================================================================== v.1 (kuso@npj)
*/
class RL_Principal_Storage_Db extends RL_Principal_Storage
{
   private $table = "users";

   public function __construct( RL_Principal $principal )
   {
     parent::__construct( $principal );

     if (isset($rh->principal_storage_model_table)) {
       $this->table = $rh->principal_storage_model_table;
     }

     $this->db_table = $principal->ctx->db->db_prefix.$this->table;
   }

   public function loadById($id) 
   { 
     $sql = "SELECT * FROM ".$this->db_table.
            " WHERE active=1 AND user_id=".$this->rh->ctx->db->Quote($id);
     $user_data = $this->rh->ctx->db->QueryOne( $sql );


     if ($user_data === false) {
     	 return false;
     }

     return $user_data;
   }
   
   public function loadByLogin($login, $realm = "") 
   { 
   	 //die(print_r($this->rh)); 
     $sql = "SELECT * FROM ".$this->db_table.
            " WHERE active=1 ".
            " AND login=".$this->rh->ctx->db->quote($login).
            " AND realm=".$this->rh->ctx->db->quote($realm);
     
     $user_data = $this->rh->ctx->db->QueryOne( $sql );
	
     if ($user_data === false) {
     	 return false;
     }

     return $user_data;
   }

   public function setStoredPassword( $user_data, $new_invariant )
   { 
     $login = $user_data["login"];
     $realm = $user_data["realm"];
     $sql = "update ".$this->db_table.
            " set stored_invariant = ".$this->rh->ctx->db->Quote($new_invariant).
            " where ".
            "     login=".$this->rh->ctx->db->Quote($login).
            " and realm=".$this->rh->ctx->db->Quote($realm);
     $this->rh->db->Query( $sql );
     return true; 
   }

   protected function _setLoginDatetime( $user_data, $datetime )
   {
     $login = $user_data["login"];
     $realm = $user_data["realm"];
     $dt = date("Y-m-d H:i:s", $datetime );
     $sql = "update ".$this->db_table.
            " set login_datetime = ".$this->rh->ctx->db->Quote($dt).
            " where ".
            "     login=".$this->rh->ctx->db->Quote($login).
            " and realm=".$this->rh->ctx->db->Quote($realm);
     $this->rh->ctx->db->Query( $sql );
     return true; 
   }


// EOC{ PrincipalStorage_db }
}


?>
